
#include "sle_low_latency.h"

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "cmsis_os2.h"
#include "app_init.h"
#include "soc_osal.h"

#include "common_def.h"
#include "pinctrl.h"
#include "uart.h"

#include "securec.h"
#include "sle_device_discovery.h"
#include "sle_errcode.h"

#include "lwip/nettool/misc.h"
#include "lwip/ip4_addr.h"
#include "lwip/netif.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"

#include "watchdog.h"
#include "i2c.h"
#include "osal_debug.h"

#include "gpio.h"

#include "adc.h"
#include "adc_porting.h"

#include "securec.h"
#include "sle_uart_server.h"
#include "sle_uart_server_adv.h"
#include "sle_device_discovery.h"
#include "sle_errcode.h"

#include "mydevice/mydevice.h"
#include "module/sht3x/sht3x.h"
#include "module/rgb/rgb.h"

#include "function/redoor/redoor.h"
// #include "function/xor/xor.h"
// // [!新增] 定义全局密钥（需与接收端一致）
// static const char xor_key[] = "MySecretKey123";  // 长度建议8-16字节
// static const size_t xor_key_len = sizeof(xor_key)-1;  // 自动计算有效长度


char send_data[100]={0};
SensorData othData = {
    .ligBuffer = "",  // 初始化为空字符串
    .humidity = "",
    .temperature = "",
    .soilHum = "",
    .id = 0
};
enum state bearpi_oth_flag = CONNECTING;
ControlState othControl;

#define SLE_UART_TASK_PRIO                  28
#define SLE_UART_TASK_DURATION_MS           2000

static uint8_t g_app_uart_int_rx_flag = 0;

static uint8_t g_app_uart_rx_buff[UART_TRANSFER_SIZE] = { 0 };

static uart_buffer_config_t uart_buffer_config = {
    .rx_buffer = g_app_uart_rx_buff,
    .rx_buffer_size = UART_TRANSFER_SIZE
};


#define SLE_UART_TASK_STACK_SIZE            0x1200
#define SLE_ADV_HANDLE_DEFAULT              1
#define SLE_UART_SERVER_MSG_QUEUE_LEN       5
#define SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE  32
#define SLE_UART_SERVER_QUEUE_DELAY         0xFFFFFFFF

#define GATHER_TASK_STACK_SIZE 0x1000
#define GATHER_TASK_PRIO (osPriority_t)(17)



unsigned long g_sle_uart_server_msgqueue_id;
#include <string.h> // for strlen, strstr
static void ssaps_server_read_request_cbk(uint8_t server_id, uint16_t conn_id, ssaps_req_read_cb_t *read_cb_para,
    errcode_t status)
{
    osal_printk("%s ssaps read request cbk callback server_id:%x, conn_id:%x, handle:%x, status:%x\r\n",
        SLE_LOG, server_id, conn_id, read_cb_para->handle, status);
}

static void ssaps_server_write_request_cbk(uint8_t server_id, uint16_t conn_id, ssaps_req_write_cb_t *write_cb_para, errcode_t status)
{
    osal_printk("%s ssaps write request callback cbk server_id:%x, conn_id:%x, handle:%x, status:%x\r\n",
        SLE_LOG, server_id, conn_id, write_cb_para->handle, status);

    if ((write_cb_para->length > 0) && write_cb_para->value) {
        osal_printk("\n sle uart recived data : %s\r\n", write_cb_para->value);

        // 解析数据
        char *data = (char *)write_cb_para->value;
        char fanFlag[2] = {0};
        char waterFlag[2] = {0};
        char sunFlag[2] = {0};
        char switchFlag[2] = {0};
        char r[3] = {0};
        char g[3] = {0};
        char b[3] = {0};
        // 0fF:1,wF:1,sF:0,swF:1,r:1,g:1,b:1,
        if(write_cb_para->length<=sizeof(uint16_t)){
            uint16_t received_conn_id = *((uint16_t *)write_cb_para->value);
            osal_printk("Received conn_id from master: %d\r\n", received_conn_id);
            othData.id=received_conn_id;
        }
        if (sscanf(data, "fF:%1[^,],wF:%1[^,],sF:%1[^,],swF:%1[^,],r:%2[^,],g:%2[^,],b:%2[^,]",
                   fanFlag, waterFlag, sunFlag, switchFlag, r, g, b) == 7) {
            // 更新 othControl 结构体
            strcpy((char *)othControl.fanFlag, fanFlag);
            strcpy((char *)othControl.waterFlag, waterFlag);
            strcpy((char *)othControl.sunFlag, sunFlag);
            strcpy((char *)othControl.switchFlag, switchFlag);
            strcpy((char *)othControl.colorNum[0], r);
            strcpy((char *)othControl.colorNum[1], g);
            strcpy((char *)othControl.colorNum[2], b);

            osal_printk("Parse success: fF=%s, wF=%s, sF=%s, swF=%s, r=%s, g=%s, b=%s\r\n",
                        fanFlag, waterFlag, sunFlag, switchFlag, r, g, b);
        } else {
            osal_printk("Parse error: \r\n");
        }

        control(&othControl);
    }
}
static void sle_uart_server_create_msgqueue(void)
{
    if (osal_msg_queue_create("sle_uart_server_msgqueue", SLE_UART_SERVER_MSG_QUEUE_LEN, \
        (unsigned long *)&g_sle_uart_server_msgqueue_id, 0, SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE) != OSAL_SUCCESS) {
        osal_printk("^%s sle_uart_server_create_msgqueue message queue create failed!\n", SLE_LOG);
    }
}

static void sle_uart_server_delete_msgqueue(void)
{
    osal_msg_queue_delete(g_sle_uart_server_msgqueue_id);
}

static void sle_uart_server_write_msgqueue(uint8_t *buffer_addr, uint16_t buffer_size)
{
    osal_msg_queue_write_copy(g_sle_uart_server_msgqueue_id, (void *)buffer_addr, \
                              (uint32_t)buffer_size, 0);
}

static int32_t sle_uart_server_receive_msgqueue(uint8_t *buffer_addr, uint32_t *buffer_size)
{
    int32_t result;

    // 从消息队列中读取数据
    result = osal_msg_queue_read_copy(g_sle_uart_server_msgqueue_id, (void *)buffer_addr, buffer_size, SLE_UART_SERVER_QUEUE_DELAY);

    return result;
}


static void sle_uart_server_rx_buf_init(uint8_t *buffer_addr, uint32_t *buffer_size)
{
    *buffer_size = SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE;
    (void)memset_s(buffer_addr, *buffer_size, 0, *buffer_size);
}
void light_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next)
{
    // UNUSED(next);
    light_data_treating(ch, buffer, length, next, &othData);
    
}
void soilHum_adc_callback(uint8_t ch, uint32_t *buffer, uint32_t length, bool *next){
    soilHum_data_treating(ch, buffer, length, next, &othData);
}
static void *sle_uart_server_task(const char *arg)
{
    unused(arg);
    uint8_t rx_buf[SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE] = {0};
    uint32_t rx_length = SLE_UART_SERVER_MSG_QUEUE_MAX_SIZE;
    uint8_t sle_connect_state[] = "sle_dis_connect";
    uint8_t sle_connected_state[] = "sle_connected";

    sle_uart_server_create_msgqueue();
    sle_uart_server_register_msg(sle_uart_server_write_msgqueue);
    sle_uart_server_init(ssaps_server_read_request_cbk, ssaps_server_write_request_cbk);
    uint8_t ret;
    while (1) {
        sle_uart_server_rx_buf_init(rx_buf, &rx_length);
        sle_uart_server_receive_msgqueue(rx_buf, &rx_length);
        //检查是否收到断开连接
        if (strncmp((const char *)rx_buf, (const char *)sle_connect_state, sizeof(sle_connect_state)) == 0) {
            ret = sle_start_announce(SLE_ADV_HANDLE_DEFAULT);
            if (ret != ERRCODE_SLE_SUCCESS) {
                osal_printk("%s sle_connect_state_changed_cbk,sle_start_announce fail :%02x\r\n",
                    SLE_LOG, ret);
            }
            else{
                bearpi_oth_flag=CONNECTING;
            }
        }
        // 检查是否收到连接的指令
        else if (strncmp((const char *)rx_buf, (const char *)sle_connected_state, sizeof(sle_connected_state)) == 0) {
            bearpi_oth_flag=READY;// 切换为已连接状态
            osal_printk("%s sle_connected\r\n", SLE_LOG);
        }
        osal_msleep(SLE_UART_TASK_DURATION_MS);
    }
    sle_uart_server_delete_msgqueue();
    return NULL;
}

static void sle_uart_entry(void)
{
    osal_task *task_handle = NULL;
    osal_kthread_lock();
    task_handle = osal_kthread_create((osal_kthread_handler)sle_uart_server_task, 0, "SLEUartServerTask",
                                      SLE_UART_TASK_STACK_SIZE);
    if (task_handle != NULL) {
        osal_kthread_set_priority(task_handle, SLE_UART_TASK_PRIO);
    }
    osal_kthread_unlock();
}

static void *gather_task(const char *arg)  
{
    UNUSED(arg);

    while (1)
    {
        if(othControl.switchFlag){
            bearpi_oth_flag=STOP;
        }
        
        switch (bearpi_oth_flag)
        {
        case READY:
            RGB_Init();
            init_fan();
            init_water();
            float temp = 0.0f;
            float humi = 0.0f;

           //开启sht3x
            sht30_Port_Init();

           //光照初始化
            uapi_adc_init(ADC_CLOCK_500KHZ);
            uapi_adc_power_en(AFE_SCAN_MODE_MAX_NUM, true);
            adc_scan_config_t config = {
                .type = 0,
                .freq = 1,
            };
            //旋转门初始化
            SensorStates states;
            
            // 初始化：偏差0.5，时间间隔2秒
            init_sensor_states(&states, 0.5f, 2.0f);
            break;
        case RUNNING:
            
                sht30_start_measurement();
                if (sht30_read_data(&temp, &humi) == 0){
                    sprintf(othData.temperature, "%.2f", temp);
                    sprintf(othData.humidity, "%.2f", humi);

                }else {
                    osal_printk("error");
                    osDelay(200);
                }
                // set_fan_in();
                // RGB_SetColor(255, 0, 0);
                // 光照
                uapi_adc_auto_scan_ch_enable(ADC_CHANNEL_2, config, light_adc_callback);
                uapi_adc_auto_scan_ch_disable(ADC_CHANNEL_2);

                //土壤
                uapi_adc_auto_scan_ch_enable(ADC_CHANNEL_3, config, soilHum_adc_callback);
                uapi_adc_auto_scan_ch_disable(ADC_CHANNEL_3);

                // 判断是否需要发送
                if (should_send_data(&othData, &states)) {
                    // 发送数据...
                    print_sensor_data(&othData);//打印一下
                    //--------------------------------------
                    snprintf(send_data, sizeof(send_data), "2,Hum:%s,Tem:%s,Lig:%s,SoilHum:%s,over", othData.humidity, othData.temperature,othData.ligBuffer,othData.soilHum);
                    if (sle_uart_client_is_connected()) {
                        sle_uart_server_send_report_by_handle((const uint8_t *)send_data, strlen(send_data));
                    } else {
                        osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
                    }

/*  
                    // [!修改] 获取实际生成的数据长度
                    int data_len = snprintf(send_data, sizeof(send_data),  // [!注意这里逗号改为分号
                    "2,Hum:%s,Tem:%s,Lig:%s,SoilHum:%s,over", 
                    othData.humidity, othData.temperature,
                    othData.ligBuffer, othData.soilHum);

                    // [!新增] 执行原地异或加密
                    xor_crypt_inplace(send_data, data_len, xor_key, xor_key_len);

                    if (sle_uart_client_is_connected()) {
                        // [!重要修改] 改用实际数据长度（不能用strlen！）
                        sle_uart_server_send_report_by_handle(
                            (const uint8_t *)send_data, 
                            data_len  // [!关键] 加密后数据可能包含\0，必须用data_len
                        );
                    } else {
                        osal_printk("%s 星闪未连接! \r\n", SLE_LOG);
                    }*/
                }
                else{
                    osal_printk("%s压缩中! \r\n", XZM_LOG);
                }
            
            break;
        case STOP:
        break;

        default:
            break;
        
        
            
            // print_sensor_data
        }
        osal_printk("A running\r\n");
        osal_msleep(2000);
    }

    return NULL;
}

static void gather_entry(void)
{
    osThreadAttr_t attr;

    attr.name = "gatherTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = GATHER_TASK_STACK_SIZE;
    attr.priority = GATHER_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)gather_task, NULL, &attr) == NULL)
    {
        osal_printk("Failed to create gather task.\r\n");
        osal_printk("创建采集任务失败！\r\n");
    }
}

app_run(gather_entry);
app_run(sle_uart_entry);